from flask import Flask, Blueprint
from flask_cors import CORS
from apps.settings import Config
import pkgutil
import sys
from logging.handlers import RotatingFileHandler
import logging
import os
from common.sql_helper import init_pool
from common.error_handler import init_error_handler


def create_app(config_name):
    app = Flask(__name__)

    # 读取配置信息
    app.config.from_object(Config.get(config_name))

    #  r'/*' 是通配符，让本服务器所有的 URL 都允许跨域请求
    CORS(app, resources=r'/*')

    # 初始化日志
    init_log(app)

    # 初始化异常处理
    init_error_handler(app)

    # 初始化蓝图
    register_bp(app)

    # 初始化连接池
    init_pool(app)

    # 打印路由关系表
    app.logger.info(f"路由关系 URL_MAP:\n{app.url_map}")
    app.logger.info("初始化完成, 返回APP")
    return app


def init_log(app: Flask):
    app.logger.setLevel(logging.DEBUG)
    log_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "log", "flask.log")
    fmt = "%(asctime)s - %(filename)s - %(funcName)s - %(lineno)d - %(levelname)s - %(message)s"
    formatter = logging.Formatter(fmt)
    fh = RotatingFileHandler(
        log_path,
        maxBytes=1024 * 1024 * 1,
        backupCount=10,
        encoding="utf-8"
    )
    fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)
    app.logger.addHandler(fh)
    app.logger.info("初始化日志完成")


def register_bp(app: Flask):
    # 遍历apps包下的所有模块
    for filefinder, name, ispkg in pkgutil.walk_packages(__path__, __name__ + "."):
        if str(name).endswith("_view"):  # 找出_view结尾的模块
            __import__(name)  # 引入模块
            module = sys.modules[name]  # 获取模块
            for i in dir(module):  # dir()列出模块中的类、方法、变量，进行遍历
                var = getattr(module, i)  # 获取变量
                if isinstance(var, Blueprint):  # 找到蓝图, 拼接项目前缀 /api/ 进行注册
                    url_prefix = var.url_prefix if var.url_prefix else ""
                    app.register_blueprint(var, url_prefix="/api/" + url_prefix)
    app.logger.info("初始化蓝图完成")
